package com.zhx.common.common.event.Listener;

import com.zhx.common.common.constant.MQConstant;
import com.zhx.common.common.domain.dto.MsgSendMessageDTO;
import com.zhx.common.common.event.MessageSendEvent;
import com.zhx.common.common.util.MQProducer;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;
import org.springframework.util.concurrent.ListenableFutureCallback;

import javax.annotation.Resource;


@Component
@Slf4j
public class MessageSendListener {

    @Resource
    private MQProducer mqProducer;

    /**
     * TransactionPhase.BEFORE_COMMIT 在事务提交之前执行
     * @param event
     */
    @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT, classes = MessageSendEvent.class, fallbackExecution = true)
    public void messageRoute(MessageSendEvent event) {
        Long msgId = event.getMsgId();
        mqProducer.sendMsg(MQConstant.SEND_MSG_TOPIC, new MsgSendMessageDTO(msgId));
    }
}
